package com.teamin.web.https.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.ConnectException;
import java.util.Iterator;
import java.util.Map;

/**
 * 公众平台通用接口工具类
 * 
 * @author liuyq
 * @date 2013-08-09
 */
public class OkHttpRequest {

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	/**
	 * 发起https请求并获取结果
	 * 
	 * @param requestUrl
	 *            请求地址
	 * @param requestMethod
	 *            请求方式（GET、POST）
	 *            提交的数据
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 */

	public static JSONObject httpsRequestMap(String requestUrl, String requestMethod, Map<String, String> para) {
		StringBuffer params = new StringBuffer();
		if (para != null && para.size() != 0) {
			Iterator<?> it = para.entrySet().iterator();
			while (it.hasNext()) {
				@SuppressWarnings("rawtypes")
				Map.Entry element = (Map.Entry) it.next();
				params.append(element.getKey());
				params.append("=");
				params.append(element.getValue());
				params.append("&");
			}
			if (params.length() > 0) {
				params.deleteCharAt(params.length() - 1);
			}
		}
		return request(requestUrl, requestMethod, params.toString());
	}

	private static JSONObject httpsRequest(String requestUrl, String requestMethod, Map<String, String> headers, String outputStr) {
		JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();
		try {
			OkHttpClient.Builder mBuilder = new OkHttpClient.Builder();
			mBuilder.sslSocketFactory(HttpsUtils.createSSLSocketFactory());
			mBuilder.hostnameVerifier(new HttpsUtils.TrustAllHostnameVerifier());
			OkHttpClient okHttpClient = mBuilder.build();

			Request request = new Request.Builder().url(requestUrl).build();
			Call call = okHttpClient.newCall(request);
			return JSON.parseObject(call.execute().body().string()) ;
		} catch (ConnectException ce) {
			ce.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonObject;
	}

	public static JSONObject request(String requestUrl, String requestMethod, String outputStr) {
		return request(requestUrl, requestMethod, null, outputStr);
	}

	public static JSONObject request(String requestUrl, String requestMethod, Map<String, String> headers, String outputStr) {
		if (requestUrl.toLowerCase().startsWith("https")) {
			return httpsRequest(requestUrl, requestMethod, headers, outputStr);
		} else {
			return httpRequest(requestUrl, requestMethod, headers, outputStr);
		}
	}

	private static JSONObject httpRequest(String requestUrl, String requestMethod, Map<String, String> headers, String outputStr) {
		try {

		OkHttpClient okHttpClient = new OkHttpClient();
		Request request = null;
		if("POST".equalsIgnoreCase(requestMethod.toUpperCase())) {
			MediaType mediaType = MediaType.parse("application/json");
			RequestBody requestBody = RequestBody.create(mediaType,outputStr);
			request = request = new Request.Builder().url(requestUrl).post(requestBody).build();
		}else if("GET".equalsIgnoreCase(requestMethod.toUpperCase())) {
			request = new Request.Builder().url(requestUrl).build();
		}
		Response response = okHttpClient.newCall(request).execute();
		return JSON.parseObject(response.body().string());
		}catch(Exception e) {
		}
		return null ;
	}

}